


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Building Finite State Machine Actors (Java) &mdash; Akka Documentation</title>
    
    <link rel="stylesheet" href="../_static/style.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../_static/prettify.css" type="text/css" />
    <link rel="stylesheet" href="../_static/base.css" type="text/css" />
    <link rel="stylesheet" href="../_static/docs.css" type="text/css" />
    <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Exo:300,400,600,700" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '2.0.1',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/toc.js"></script>
    <script type="text/javascript" src="../_static/prettify.js"></script>
    <script type="text/javascript" src="../_static/highlightCode.js"></script>
    <script type="text/javascript" src="../_static/effects.core.js"></script>
    <script type="text/javascript" src="../_static/effects.highlight.js"></script>
    <script type="text/javascript" src="../_static/scrollTo.js"></script>
    <script type="text/javascript" src="../_static/contentsFix.js"></script>
    <link rel="shortcut icon" href="../_static/favicon.ico"/>
    <link rel="top" title="Akka Documentation" href="../index.html" />
    <link rel="up" title="Java API" href="index.html" />
    <link rel="next" title="Akka Extensions (Java)" href="extending-akka.html" />
    <link rel="prev" title="Transactors (Java)" href="transactors.html" /> 
  </head>
  <body>
  <div class="navbar">
    <div class="navbar-inner">
      <div class="container">
        <div class="navbar-logo">
          <a href="http://akka.io"><img src="../_static/logo-small.png" /></a>
        </div>    
        <ul class="nav">
          <li><a href="http://akka.io/docs">Documentation</a></li>
          <li><a href="http://akka.io/downloads">Download</a></li>
          <li><a href="http://groups.google.com/group/akka-user">Mailing List</a></li>
          <li><a href="http://github.com/akka/akka">Code</a></li>           
          <li><a href="http://typesafe.com/products/typesafe-subscription">Commerical Support</a></li>
        </ul>
      </div>
    </div>
  </div>
  <div class="main">
    <div class="container">
      <div class="page-title">Building Finite State Machine Actors (Java)</div><div class="pdf-link"><a href="http://akka.io/docs/akka/2.0.1/Akka.pdf"><img src="../_static/pdf-icon.png" style="height: 40px;" /></a></div></div>
    <div class="main-container">
      <div class="container">
        <div class="row">
          <div class="span12">
            <ul class="breadcrumb">           
              <li>
                 <span class="divider">|</span> <a href="extending-akka.html">Akka Extensions (Java)</a> <span class="divider">»</span>
              </li>
              <li>
                <a href="../index.html">Contents</a>
              </li>
              <li>
                <span class="divider">«</span> <a href="transactors.html">Transactors (Java)</a> <span class="divider">|</span>
              </li>
              <li>
                Version 2.0.1
              </li>
            </ul>         
          </div>
        </div>
        <div class="row">
          <div class="span9">
            
  <div class="section" id="building-finite-state-machine-actors-java">
<span id="fsm-java"></span><h1>Building Finite State Machine Actors (Java)</h1>
<div class="section" id="overview">
<h2>Overview</h2>
<p>The FSM (Finite State Machine) pattern is best described in the <a class="reference external" href="http://www.erlang.org/documentation/doc-4.8.2/doc/design_principles/fsm.html">Erlang design
principles</a>.
In short, it can be seen as a set of relations of the form:</p>
<blockquote>
<div><strong>State(S) x Event(E) -&gt; Actions (A), State(S&#8217;)</strong></div></blockquote>
<p>These relations are interpreted as meaning:</p>
<blockquote>
<div><em>If we are in state S and the event E occurs, we should perform the actions A
and make a transition to the state S&#8217;.</em></div></blockquote>
<p>While the Scala programming language enables the formulation of a nice internal
DSL (domain specific language) for formulating finite state machines (see
<a class="reference internal" href="../scala/fsm.html#fsm-scala"><em>FSM</em></a>), Java’s verbosity does not lend itself well to the same
approach. This chapter describes ways to effectively achieve the same
separation of concerns through self-discipline.</p>
</div>
<div class="section" id="how-state-should-be-handled">
<h2>How State should be Handled</h2>
<p>All mutable fields (or transitively mutable data structures) referenced by the
FSM actor’s implementation should be collected in one place and only mutated
using a small well-defined set of methods. One way to achieve this is to
assemble all mutable state in a superclass which keeps it private and offers
protected methods for mutating it.</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">import</span> <span class="nn">java.util.ArrayList</span><span class="o">;</span>
<span class="k">import</span> <span class="nn">java.util.List</span><span class="o">;</span>
<span class="k">import</span> <span class="nn">akka.actor.ActorRef</span><span class="o">;</span>
</pre></div>
</div>
<div class="highlight-scala"><div class="highlight"><pre><span class="n">static</span> <span class="k">abstract</span> <span class="k">class</span> <span class="nc">MyFSMBase</span> <span class="k">extends</span> <span class="nc">UntypedActor</span> <span class="o">{</span>

  <span class="cm">/*</span>
<span class="cm">   * This is the mutable state of this state machine.</span>
<span class="cm">   */</span>
  <span class="k">protected</span> <span class="n">enum</span> <span class="nc">State</span> <span class="o">{</span>
    <span class="nc">IDLE</span><span class="o">,</span> <span class="nc">ACTIVE</span><span class="o">;</span>
  <span class="o">}</span>

  <span class="k">private</span> <span class="nc">State</span> <span class="n">state</span> <span class="k">=</span> <span class="nc">State</span><span class="o">.</span><span class="nc">IDLE</span><span class="o">;</span>
  <span class="k">private</span> <span class="nc">ActorRef</span> <span class="n">target</span><span class="o">;</span>
  <span class="k">private</span> <span class="nc">List</span><span class="o">&lt;</span><span class="nc">Object</span><span class="o">&gt;</span> <span class="n">queue</span><span class="o">;</span>

  <span class="cm">/*</span>
<span class="cm">   * Then come all the mutator methods:</span>
<span class="cm">   */</span>
  <span class="k">protected</span> <span class="n">void</span> <span class="n">init</span><span class="o">(</span><span class="nc">ActorRef</span> <span class="n">target</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">this</span><span class="o">.</span><span class="n">target</span> <span class="k">=</span> <span class="n">target</span><span class="o">;</span>
    <span class="n">queue</span> <span class="k">=</span> <span class="k">new</span> <span class="nc">ArrayList</span><span class="o">&lt;</span><span class="nc">Object</span><span class="o">&gt;();</span>
  <span class="o">}</span>

  <span class="k">protected</span> <span class="n">void</span> <span class="n">setState</span><span class="o">(</span><span class="nc">State</span> <span class="n">s</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">if</span> <span class="o">(</span><span class="n">state</span> <span class="o">!=</span> <span class="n">s</span><span class="o">)</span> <span class="o">{</span>
      <span class="n">transition</span><span class="o">(</span><span class="n">state</span><span class="o">,</span> <span class="n">s</span><span class="o">);</span>
      <span class="n">state</span> <span class="k">=</span> <span class="n">s</span><span class="o">;</span>
    <span class="o">}</span>
  <span class="o">}</span>

  <span class="k">protected</span> <span class="n">void</span> <span class="n">enqueue</span><span class="o">(</span><span class="nc">Object</span> <span class="n">o</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">if</span> <span class="o">(</span><span class="n">queue</span> <span class="o">!=</span> <span class="kc">null</span><span class="o">)</span>
      <span class="n">queue</span><span class="o">.</span><span class="n">add</span><span class="o">(</span><span class="n">o</span><span class="o">);</span>
  <span class="o">}</span>

  <span class="k">protected</span> <span class="nc">List</span><span class="o">&lt;</span><span class="nc">Object</span><span class="o">&gt;</span> <span class="n">drainQueue</span><span class="o">()</span> <span class="o">{</span>
    <span class="k">final</span> <span class="nc">List</span><span class="o">&lt;</span><span class="nc">Object</span><span class="o">&gt;</span> <span class="n">q</span> <span class="k">=</span> <span class="n">queue</span><span class="o">;</span>
    <span class="k">if</span> <span class="o">(</span><span class="n">q</span> <span class="o">==</span> <span class="kc">null</span><span class="o">)</span>
      <span class="k">throw</span> <span class="k">new</span> <span class="nc">IllegalStateException</span><span class="o">(</span><span class="s">&quot;drainQueue(): not yet initialized&quot;</span><span class="o">);</span>
    <span class="n">queue</span> <span class="k">=</span> <span class="k">new</span> <span class="nc">ArrayList</span><span class="o">&lt;</span><span class="nc">Object</span><span class="o">&gt;();</span>
    <span class="k">return</span> <span class="n">q</span><span class="o">;</span>
  <span class="o">}</span>

  <span class="cm">/*</span>
<span class="cm">   * Here are the interrogation methods:</span>
<span class="cm">   */</span>
  <span class="k">protected</span> <span class="n">boolean</span> <span class="n">isInitialized</span><span class="o">()</span> <span class="o">{</span>
    <span class="k">return</span> <span class="n">target</span> <span class="o">!=</span> <span class="kc">null</span><span class="o">;</span>
  <span class="o">}</span>

  <span class="k">protected</span> <span class="nc">State</span> <span class="n">getState</span><span class="o">()</span> <span class="o">{</span>
    <span class="k">return</span> <span class="n">state</span><span class="o">;</span>
  <span class="o">}</span>

  <span class="k">protected</span> <span class="nc">ActorRef</span> <span class="n">getTarget</span><span class="o">()</span> <span class="o">{</span>
    <span class="k">if</span> <span class="o">(</span><span class="n">target</span> <span class="o">==</span> <span class="kc">null</span><span class="o">)</span>
      <span class="k">throw</span> <span class="k">new</span> <span class="nc">IllegalStateException</span><span class="o">(</span><span class="s">&quot;getTarget(): not yet initialized&quot;</span><span class="o">);</span>
    <span class="k">return</span> <span class="n">target</span><span class="o">;</span>
  <span class="o">}</span>

  <span class="cm">/*</span>
<span class="cm">   * And finally the callbacks (only one in this example: react to state change)</span>
<span class="cm">   */</span>
  <span class="k">abstract</span> <span class="k">protected</span> <span class="n">void</span> <span class="n">transition</span><span class="o">(</span><span class="nc">State</span> <span class="n">old</span><span class="o">,</span> <span class="nc">State</span> <span class="n">next</span><span class="o">);</span>
<span class="o">}</span>
</pre></div>
</div>
<p>The benefit of this approach is that state changes can be acted upon in one
central place, which makes it impossible to forget inserting code for reacting
to state transitions when adding to the FSM’s machinery.</p>
</div>
<div class="section" id="message-buncher-example">
<h2>Message Buncher Example</h2>
<p>The base class shown above is designed to support a similar example as for the
Scala FSM documentation: an actor which receives and queues messages, to be
delivered in batches to a configurable target actor. The messages involved are:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="n">public</span> <span class="n">static</span> <span class="k">final</span> <span class="k">class</span> <span class="nc">SetTarget</span> <span class="o">{</span>
  <span class="k">final</span> <span class="nc">ActorRef</span> <span class="n">ref</span><span class="o">;</span>

  <span class="n">public</span> <span class="nc">SetTarget</span><span class="o">(</span><span class="nc">ActorRef</span> <span class="n">ref</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">this</span><span class="o">.</span><span class="n">ref</span> <span class="k">=</span> <span class="n">ref</span><span class="o">;</span>
  <span class="o">}</span>
<span class="o">}</span>

<span class="n">public</span> <span class="n">static</span> <span class="k">final</span> <span class="k">class</span> <span class="nc">Queue</span> <span class="o">{</span>
  <span class="k">final</span> <span class="nc">Object</span> <span class="n">o</span><span class="o">;</span>

  <span class="n">public</span> <span class="nc">Queue</span><span class="o">(</span><span class="nc">Object</span> <span class="n">o</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">this</span><span class="o">.</span><span class="n">o</span> <span class="k">=</span> <span class="n">o</span><span class="o">;</span>
  <span class="o">}</span>
<span class="o">}</span>

<span class="n">public</span> <span class="n">static</span> <span class="k">final</span> <span class="nc">Object</span> <span class="n">flush</span> <span class="k">=</span> <span class="k">new</span> <span class="nc">Object</span><span class="o">();</span>

<span class="n">public</span> <span class="n">static</span> <span class="k">final</span> <span class="k">class</span> <span class="nc">Batch</span> <span class="o">{</span>
  <span class="k">final</span> <span class="nc">List</span><span class="o">&lt;</span><span class="nc">Object</span><span class="o">&gt;</span> <span class="n">objects</span><span class="o">;</span>

  <span class="n">public</span> <span class="nc">Batch</span><span class="o">(</span><span class="nc">List</span><span class="o">&lt;</span><span class="nc">Object</span><span class="o">&gt;</span> <span class="n">objects</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">this</span><span class="o">.</span><span class="n">objects</span> <span class="k">=</span> <span class="n">objects</span><span class="o">;</span>
  <span class="o">}</span>
<span class="o">}</span>
</pre></div>
</div>
<p>This actor has only the two states <tt class="docutils literal"><span class="pre">IDLE</span></tt> and <tt class="docutils literal"><span class="pre">ACTIVE</span></tt>, making their
handling quite straight-forward in the concrete actor derived from the base
class:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">import</span> <span class="nn">akka.event.LoggingAdapter</span><span class="o">;</span>
<span class="k">import</span> <span class="nn">akka.event.Logging</span><span class="o">;</span>
<span class="k">import</span> <span class="nn">akka.actor.UntypedActor</span><span class="o">;</span>
</pre></div>
</div>
<div class="highlight-scala"><div class="highlight"><pre><span class="n">static</span> <span class="n">public</span> <span class="k">class</span> <span class="nc">MyFSM</span> <span class="k">extends</span> <span class="nc">MyFSMBase</span> <span class="o">{</span>

  <span class="k">private</span> <span class="k">final</span> <span class="nc">LoggingAdapter</span> <span class="n">log</span> <span class="k">=</span> <span class="nc">Logging</span><span class="o">.</span><span class="n">getLogger</span><span class="o">(</span><span class="n">getContext</span><span class="o">().</span><span class="n">system</span><span class="o">(),</span> <span class="k">this</span><span class="o">);</span>

  <span class="nd">@Override</span>
  <span class="n">public</span> <span class="n">void</span> <span class="n">onReceive</span><span class="o">(</span><span class="nc">Object</span> <span class="n">o</span><span class="o">)</span> <span class="o">{</span>

    <span class="k">if</span> <span class="o">(</span><span class="n">getState</span><span class="o">()</span> <span class="o">==</span> <span class="nc">State</span><span class="o">.</span><span class="nc">IDLE</span><span class="o">)</span> <span class="o">{</span>

      <span class="k">if</span> <span class="o">(</span><span class="n">o</span> <span class="n">instanceof</span> <span class="nc">SetTarget</span><span class="o">)</span>
        <span class="n">init</span><span class="o">(((</span><span class="nc">SetTarget</span><span class="o">)</span> <span class="n">o</span><span class="o">).</span><span class="n">ref</span><span class="o">);</span>

      <span class="k">else</span>
        <span class="n">whenUnhandled</span><span class="o">(</span><span class="n">o</span><span class="o">);</span>

    <span class="o">}</span> <span class="k">else</span> <span class="k">if</span> <span class="o">(</span><span class="n">getState</span><span class="o">()</span> <span class="o">==</span> <span class="nc">State</span><span class="o">.</span><span class="nc">ACTIVE</span><span class="o">)</span> <span class="o">{</span>

      <span class="k">if</span> <span class="o">(</span><span class="n">o</span> <span class="o">==</span> <span class="n">flush</span><span class="o">)</span>
        <span class="n">setState</span><span class="o">(</span><span class="nc">State</span><span class="o">.</span><span class="nc">IDLE</span><span class="o">);</span>

      <span class="k">else</span>
        <span class="n">whenUnhandled</span><span class="o">(</span><span class="n">o</span><span class="o">);</span>
    <span class="o">}</span>
  <span class="o">}</span>

  <span class="nd">@Override</span>
  <span class="n">public</span> <span class="n">void</span> <span class="n">transition</span><span class="o">(</span><span class="nc">State</span> <span class="n">old</span><span class="o">,</span> <span class="nc">State</span> <span class="n">next</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">if</span> <span class="o">(</span><span class="n">old</span> <span class="o">==</span> <span class="nc">State</span><span class="o">.</span><span class="nc">ACTIVE</span><span class="o">)</span> <span class="o">{</span>
      <span class="n">getTarget</span><span class="o">().</span><span class="n">tell</span><span class="o">(</span><span class="k">new</span> <span class="nc">Batch</span><span class="o">(</span><span class="n">drainQueue</span><span class="o">()));</span>
    <span class="o">}</span>
  <span class="o">}</span>

  <span class="k">private</span> <span class="n">void</span> <span class="n">whenUnhandled</span><span class="o">(</span><span class="nc">Object</span> <span class="n">o</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">if</span> <span class="o">(</span><span class="n">o</span> <span class="n">instanceof</span> <span class="nc">Queue</span> <span class="o">&amp;&amp;</span> <span class="n">isInitialized</span><span class="o">())</span> <span class="o">{</span>
      <span class="n">enqueue</span><span class="o">(((</span><span class="nc">Queue</span><span class="o">)</span> <span class="n">o</span><span class="o">).</span><span class="n">o</span><span class="o">);</span>
      <span class="n">setState</span><span class="o">(</span><span class="nc">State</span><span class="o">.</span><span class="nc">ACTIVE</span><span class="o">);</span>

    <span class="o">}</span> <span class="k">else</span> <span class="o">{</span>
      <span class="n">log</span><span class="o">.</span><span class="n">warning</span><span class="o">(</span><span class="s">&quot;received unknown message {} in state {}&quot;</span><span class="o">,</span> <span class="n">o</span><span class="o">,</span> <span class="n">getState</span><span class="o">());</span>
    <span class="o">}</span>
  <span class="o">}</span>
<span class="o">}</span>
</pre></div>
</div>
<p>The trick here is to factor out common functionality like <tt class="xref py py-meth docutils literal"><span class="pre">whenUnhandled</span></tt>
and <tt class="xref py py-meth docutils literal"><span class="pre">transition</span></tt> in order to obtain a few well-defined points for
reacting to change or insert logging.</p>
</div>
<div class="section" id="state-centric-vs-event-centric">
<h2>State-Centric vs. Event-Centric</h2>
<p>In the example above, the subjective complexity of state and events was roughly
equal, making it a matter of taste whether to choose primary dispatch on
either; in the example a state-based dispatch was chosen. Depending on how
evenly the matrix of possible states and events is populated, it may be more
practical to handle different events first and distinguish the states in the
second tier. An example would be a state machine which has a multitude of
internal states but handles only very few distinct events.</p>
</div>
</div>


          </div>
          <div class="span3"><p class="contents-title">Contents</p>
              <div id="scroller-anchor">
                <div id="scroller">
                  <div id="toc"></div>
                </div>
              </div></div>
        </div>
      </div>
    </div>
  </div>
  <div class="footer">
  <div class="container">
    <ul>
      <li><h5>Akka</h5></li>
      <li><a href="http://akka.io/docs">Documentation</a></li>
      <li><a href="http://akka.io/downloads">Downloads</a></li>
    </ul>
    <ul>
      <li><h5>Contribute</h5></li>
      <li><a href="http://github.com/akka/akka">Source Code</a></li>
      <li><a href="http://groups.google.com/group/akka-user">Mailing List</a></li>      
      <li><a href="http://www.assembla.com/spaces/akka/tickets">Report a Bug</a></li>      
    </ul>
    <ul>
      <li><h5>Company</h5></li>
      <li><a href="http://typesafe.com/products/typesafe-subscription">Commercial Support</a></li>
      <li><a href="http://akka.io/team">Team</a></li>
      <li><a href="mailto:info@typesafe.com">Contact</a></li>
    </ul>
    <ul>
      <li><img src="../_static/watermark.png" align="center"/></li>
    </ul>
  </div>
  <div class="container copyright">
    <p style="float: left;">
      © 2012 <a href="http://typesafe.com/">Typesafe Inc.</a> <span class="license">Akka is Open Source and available under the Apache 2 License.</span>
    </p>
    <p style="float: right; font-size: 12px;">
      Last updated: Apr 13, 2012
    </p>          
  </div>
</div>
<script type="text/javascript">
  $('#toc').toc();
</script>
  

  </body>
</html>